[T4Scaffolding.Scaffolder(Description = "Creates a Restful service using WCF WebApi")][CmdletBinding()]
param(
	[parameter(Position = 0, Mandatory = $true, ValueFromPipelineByPropertyName = $true)][string]$ModelType,
	[string]$DbContextType,        
    [string]$Project,
	[string]$CodeLanguage,
	[switch]$NoChildItems = $false,
	[string[]]$TemplateFolders,
	[switch]$Client = $false,
	[switch]$Force = $false
)

$foundModelType = Get-ProjectType $ModelType -Project $Project -BlockUi
if (!$foundModelType) { 
	return 
}

$serviceName = $foundModelType.Name + "Service"

$primaryKey = Get-PrimaryKey $foundModelType.FullName -Project $Project -ErrorIfNotFound
if (!$primaryKey) { 
	return 
}

$outputPath = Join-Path Services ($foundModelType.Name + "Service")

$repositoryName = $foundModelType.Name + "Repository"
$defaultNamespace = (Get-Project $Project).Properties.Item("DefaultNamespace").Value
$modelTypeNamespace = [T4Scaffolding.Namespaces]::GetNamespace($foundModelType.FullName)
$serviceNamespace = [T4Scaffolding.Namespaces]::Normalize($defaultNamespace + "." + [System.IO.Path]::GetDirectoryName($outputPath).Replace([System.IO.Path]::DirectorySeparatorChar, "."))
$repositoryNamespace = [T4Scaffolding.Namespaces]::Normalize(".Models")
$modelTypePluralized = Get-PluralizedWord $foundModelType.Name

Scaffold Repository -ModelType $foundModelType.FullName -DbContextType $DbContextType -Project $Project -NoChildItems:$NoChildItems -Force:$Force -BlockUi

$serviceStartOutputPath = Join-Path App_Start ($serviceName + "Start")
Add-ProjectItemViaTemplate $serviceStartOutputPath -Template RegisterRoutesTemplate `
						   -Model @{
								ServiceName = $serviceName;
								ModelType = [MarshalByRefObject]$foundModelType;
								DefaultNamespace = $defaultNamespace;
								ServiceNamespace = $serviceNamespace;
							} `
							-SuccessMessage "Added Service AppStart output at {0}" `
							-TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force


Add-ProjectItemViaTemplate $outputPath -Template RestfulServiceTemplate `
	-Model @{
		ServiceName = $serviceName;
		RepositoryName = $repositoryName; 
		ModelType = [MarshalByRefObject]$foundModelType;
		PrimaryKey = [string]$primaryKey;
		DefaultNamespace = $defaultNamespace;
		ModelTypeNamespace = $modelTypeNamespace;
		ServiceNamespace = $serviceNamespace; 
		 } `
	-SuccessMessage "Added RestfulService output at {0}" `
	-TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force

if($Client) {
	Scaffold RestfulServiceClient $ModelType
}